'use strict'

let models = require('../models');
let errors = require('../../config/errors');

let Teacher = models.Teacher;

let SchoolDao = models.SchoolDao;
let GradeDao = models.GradeDao;
let TeacherDao = models.TeacherDao;
let AbsenceApplyDao = models.AbsenceApplyDao;

function getTeacherByUserId(userId) {
    return TeacherDao.findOne({
        user: userId  
    });
}

function getAbsenceApplyByUserId(userId){
	return AbsenceApplyDao.findOne({
		user:userId
	});
}

function updateAbseneceApply(teacher, apply) {
    AbsenceApplyDao.update({
        id: apply.id
    }, {
        $set: {
            status: apply.status
        }
    });
}

function getTeachersOfNatureClass(natureClass) {
    return TeacherDao.find({
        managedClasses: natureClass.id
    });
}

function generateSchoolOfTeacher(teacher) {
    let grades = generateGradesOfClasses(teacher.managedClasses);
    if ( grades.length == 0 ) {
        return {
            grades: [
            ]
        };
    }

    let school = SchoolDao.findOne({
        grades: grades[0].id
    });

    return {
        id: school.id,
        name: school.name,
        grades: grades,
        terms: school.terms
    };
}

function generateGradesOfClasses(natureClasses) {
    let grades = {};
    natureClasses.forEach(natureClass => {
        let grade = GradeDao.findOne({
            natureClasses: natureClass
        });

        if ( !(grade.id in grades) ) {
            grades[grade.id] = {
                id: grade.id,
                name: grade.name,
                natureClasses: [ ]
            }
        }

        grades[grade.id].natureClasses.push(natureClass);
    });

    return Object.keys(grades).map(gradeId => {
        return grades[gradeId];
    });
}

module.exports = {
    getTeacherByUserId,
    updateAbseneceApply,
    getTeachersOfNatureClass,
    generateSchoolOfTeacher
};

